package com.zhugang.week14.concurrent;

/**
 * @program algorithms
 * @description: singleton
 * @author: chanzhugang
 * @create: 2022/09/15 20:01
 */
public class Singleton {

    static class DbConnection {
        DbConnection() {
        }
    }

    /**
     * volatile 禁止指令重排
     */
    static volatile DbConnection ref;

    public static DbConnection getDb() {
        // weak atomics : acquire, release
        if (ref == null) {
            synchronized (Singleton.class) {
                System.out.println("Synchronized block pass thread:" + Thread.currentThread().getId());
                if (ref == null) {
                    // new 在jvm层面并发情况可能发生指令重排，需要用volatile禁止指令重排
                    ref = new DbConnection();
                    System.out.println("hello singleton");
                }
            }
        }
        return ref;
    }

    public static void main(String[] argv) {
        for (int i = 0; i < 200; i++) {
            new Thread(() -> {
                getDb();
            }).start();
        }
    }
}